<?php

namespace app\admin\controller;

use app\common\model\Domains;
use app\common\model\Jumps;
use think\Request;

class Jump extends Base
{

    public function index(Request $request)
    {
        $post = $request->isAjax();
        if ($post){

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);

            $data = array(
                'data'      =>  Jumps::with('domain')->order(['id'=>'desc'])->page($page)->limit($limit)->select(),
                'count'     =>  Jumps::count('id'),
                'code'      => 0,
                'msg'       => '',
            );

            return json($data);
        }

        return view();
    }


    public function create(Request $request)
    {

        if ( $request->isPost() ){

            $post = trimAll($request->post());

            // 把换行，替换成||
            $post['url'] = huanhangToStr($post['url']);

            $post['status']			= isset($post['status']) ? $post['status'] : 2;
            $post['create_time']	= time();

            //保存到数据库
            if ( Jumps::create($post) ){
                createLog('添加跳转成功：' . $post['name']);
                success('保存成功');
            }else{
                createLog('添加跳转失败：' . $post['name']);
                error('保存失败');
            }

        }else{
            $domains = Domains::where(['type'=>9, 'status'=>1])->select();
            $this->assign('domains', $domains);
            return view();
        }

    }


    public function edit(Request $request, $id)
    {

        if ( $request->isPost() ){
            $post = trimAll($request->post());

            // 把换行，替换成||
            $post['url'] = huanhangToStr($post['url']);

            $post['status']			= isset($post['status']) ? $post['status'] : 2;

            //保存到数据库
            if ( Jumps::where('id',$id)->update($post) ){
                createLog('编辑跳转成功：' . $post['name']);
                success('保存成功');
            }else{
                createLog('编辑跳转失败：' . $post['name']);
                error('保存失败');
            }

        }else{

            $data = Jumps::get($id);

            if ($data){
                // 把||，替换成换行
                $data['url'] = str_replace('||', PHP_EOL, $data['url']);
            } else {
                $data['url'] = '';
            }

            // 获取所有跳转域名
            $domains = Domains::where(['type'=>9, 'status'=>1])->select();
            $this->assign(['domains'=>$domains, 'data'=>$data]);
            return view();
        }
    }




}
